<?php
namespace apps\admin\libraries;

use enums\PriEnums;
use Phalcon\Acl;
use Phalcon\Acl\Adapter\Memory as AclList;
use Phalcon\Acl\Resource;
use Phalcon\Acl\Role;
use apps\admin\biz\PrivilegeBiz;

/**
 * AdminAcl
 *
 * @author hfc
 */
trait  TAdminAcl
{
	private $prefixAcl= 'admin_acl_';
	private $prefixRole = 'admin_role_';
	
    /**
    * 设置访问控制,菜单
    * @param int $roleId 角色id
    */
    protected function setAcl( $roleId = 0 )
    {
        if( !$roleId )
        {
            return false;
        }

        $objacl = new AclList();
        $objacl->setDefaultAction( Acl::DENY ); //不受控的操作允许访问
        
        $roleName = $this->prefixRole . $roleId; //和角色id相关
        $role = new Role( $roleName );
        $objacl->addRole( $role );
        
		//角色允许的资源
        $objBiz = new PrivilegeBiz();
        $arrResource = $objBiz->getRoleAcl( $roleId );
        
		foreach( $arrResource as $controller => $arrAction ) 
		{
			$objacl->addResource( new Resource( $controller ), $arrAction );
			$objacl->allow( $roleName, $controller, $arrAction );


            foreach ( $arrAction as $action )
            {
                $arrayAction[] = strtolower( $action );
            }
            $objacl->addResource( new Resource( strtolower( $controller ) ), $arrayAction );
            $objacl->allow( $roleName, strtolower( $controller ), $arrayAction );
		}
		
		//默认增加首页显示，否则，如果权限没有选中，会导致首页不能进入，等于网站所有网页都不能访问。
		$objacl->addResource( new Resource( 'index' ), [ 'index', 'fcmshome' ] );
        $objacl->allow( $roleName, 'index', 'index' ); 
        $objacl->allow( $roleName, 'index', 'fcmshome' ); 
        
        $aclList =  $this->prefixAcl . $roleId;
        $this->dataCache->save( $aclList,  $objacl  );
        
        //生成菜单
		$arrMenu = $objBiz->getLeftMenu( $roleId );
        $this->dataCache->save( PriEnums::LEFT_MENU_ADMIN . $roleId ,  $arrMenu  );
        return true;
    }
    
    /**
     * 是否有权限
     * @param int $roleId 角色id
     */
    protected function isAllow( $roleId )
    {
    	$aclList = $this->prefixAcl . $roleId;
    	$objacl =  $this->dataCache->get( $aclList );
    	if( ! $objacl ) //没有的话从数据库中里读取
    	{
    		$this->setAcl( $roleId );
    		$objacl = $this->dataCache->get( $aclList );
    	}
    	if( $objacl )
    	{
    		$controller = strtolower( $this->router->getControllerName());
    		$action = strtolower( $this->router->getActionName() );
    		$roleName =  $this->prefixRole . $roleId;
    		if( $objacl->isAllowed( $roleName, $controller, $action ) )
    		{
    			return array( 'status' => PriEnums::STUATUS_NOEMAL );
    		}
    		else
    		{
    			return  array( 'status' => PriEnums::STUATUS_UNNOEMAL, 'msg' => '您没有权限访问  ' . $controller . '/' . $action);
    		}
    	}
    	else
    	{
    		return array( 'status' => PriEnums::STUATUS_UNNOEMAL, 'msg' => 'acl异常错误' );
    	}
    }
}
